﻿
namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpGetUserInfoRequestHandler : IAfpRequestHandler {
        private enum UserFlags : byte {
            ThisUser = 1
        }
        private enum UserBitmap : short {
            UserId = 0x1,
            PrimaryGroupId = 0x2,
            Uuid = 0x4
        }
        #region IAfpRequestHandler Members

        public byte CommandCode {
            get { return 37; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            UserFlags flags = requestStream.ReadEnum<UserFlags>();

            if (flags != UserFlags.ThisUser) {
                return AfpResultCode.FPParamErr;
            }

            requestStream.ReadInt32(); // User ID

            UserBitmap bitmap = requestStream.ReadEnum<UserBitmap>();

            responseStream.WriteEnum(bitmap);

            foreach (UserBitmap value in bitmap.EnumerateFlags()) {
                switch (value) {
                    case UserBitmap.UserId:
                        responseStream.WriteInt32(session.UserGroupAssigner.Get(session.User.Id));
                        break;
                    case UserBitmap.Uuid:
                        responseStream.WriteBytes(session.User.Id.ToByteArray());
                        break;
                    case UserBitmap.PrimaryGroupId:
                        responseStream.WriteInt32(session.UserGroupAssigner.Get(session.User.PrimaryGroup));
                        break;
                }
            }

            return AfpResultCode.FPNoErr;
        }

        #endregion
    }
}
